package com.itchen.web;

import com.itchen.pojo.User;
import com.itchen.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author げっしょく
 * @date 2021/9/4
 */
@WebServlet("/loginUser")
public class LoginUser extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserService userService = new UserService();
        User user = userService.login(username, password);

        String remember = request.getParameter("remember");
        HttpSession session1 = request.getSession();
        String checkcode = (String) session1.getAttribute("checkcode");

            if (user != null) {

                if ("1".equals(remember)) {
                    Cookie username1 = new Cookie("username", username);
                    Cookie password1 = new Cookie("password", password);
                    username1.setMaxAge(60 * 60 * 24 * 7);
                    password1.setMaxAge(60 * 60 * 24 * 7);

                    response.addCookie(username1);
                    response.addCookie(password1);
                }
                //登录成功
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                String contextPath = request.getContextPath();

                response.sendRedirect(contextPath + "/selectAllServlet");

            } else {
                //登录失败
                request.setAttribute("login_msg", "用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
